package com.kt.uokos.yimo.controller;


import com.kt.uokos.yimo.anno.RequiresPermissionsDesc;
import com.kt.uokos.yimo.anno.validator.Order;
import com.kt.uokos.yimo.anno.validator.Sort;
import com.kt.uokos.yimo.dao.Product;
import com.kt.uokos.yimo.dao.Topic;
import com.kt.uokos.yimo.service.ProductService;
import com.kt.uokos.yimo.service.TopicService;
import com.kt.uokos.yimo.util.ResponseUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/admin/topic")
public class TopicController {
    @Resource
    private TopicService topicService;

    @Resource
    private ProductService productService;


    @GetMapping("/list")
    public Object list(String title, String subtitle,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order){
        List<Topic> topics = topicService.queryList(title, subtitle, page, limit, sort, order);
        return ResponseUtil.okList(topics);
    }

    @PostMapping("/create")
    public Object create(@RequestBody Topic topic){
        if (topic == null){
            return ResponseUtil.errs();
        }
        topicService.add(topic);
        return ResponseUtil.ok();
    }

    @PostMapping("/delete")
    public Object delete(@RequestBody Topic topic){
        if (topic == null){
            return ResponseUtil.errs();
        }
        topicService.delete(topic);
        return ResponseUtil.ok();
    }

    @PostMapping("/update")
    public Object update(@RequestBody Topic topic){
        topicService.update(topic);
        return ResponseUtil.ok();
    }


    @RequiresPermissions("admin:topic:read")
    @RequiresPermissionsDesc(menu = {"推广管理", "专题管理"}, button = "详情")
    @GetMapping("/read")
    public Object read(@NotNull Integer id){
        Topic topic = topicService.findById(id);
        Integer[] goodsIds = topic.getGoods();
        List<Product> productList;
        if (goodsIds == null && goodsIds.length == 0){
            productList = new ArrayList<>();
        }else {
             productList = productService.queryByIds(goodsIds);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("topic",topic);
        map.put("goodsList",productList);
        return ResponseUtil.ok(map);

    }
}
